package com.nd.teamfile.fileexplorer.fragment;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.common.android.utils.SdCardUtils;
import com.common.android.utils.ToastUtils;
import com.nd.teamfile.fileexplorer.R;
import com.nd.teamfile.fileexplorer.activity.FileExplorerActivity;
import com.nd.teamfile.fileexplorer.adapter.FileListAdapter;
import com.nd.teamfile.fileexplorer.helper.FileIconHelper;
import com.nd.teamfile.fileexplorer.helper.FileSortHelper;
import com.nd.teamfile.fileexplorer.sdk.type.FileExplorerInfo;
import com.nd.teamfile.fileexplorer.util.FileExplorerUtil;

/**
 * 文件浏览界面
 * 
 * @ClassName FileExplorerFragment
 * @Function TODO ADD FUNCTION
 * @Reason TODO ADD REASON
 * 
 * @author HuangYK
 * @version v1.3.3
 * @Date 2014-1-24 上午12:39:42
 * 
 * @see
 */
public class FileExplorerFragment extends Fragment {
	// 当前默认要打开哪个路径，由其他界面跳转时传递所需要用到的KEY
	public static final String CUR_PATH = "CUR_PATH";
	/**当前允许一次性上传的最大文件数*/
	private static final int MAX_UPLOAD_FILES=9;
	// ==============操作类==============
	// 图标操作类
	private FileIconHelper mFileIconHelper;
	// 排序操作类
	private FileSortHelper mFileSortHelper;

	// 当前Fragment所在的Activity
	private Activity mActivity;
	// 最外层View
	private View mRootView;

	// 顶部返回按钮
	private ImageView mIvBack;

	// ==============路径导航栏==============
	private LinearLayout mLlNavigationBar;
	// 路径导航栏中的路径选择按钮
	private LinearLayout mLlCurPathPane;
	// 路径导航栏中的路径文字
	private TextView mTvCurPath;
	// 路径导航栏中的下拉窗口
	private ScrollView mSvDropDownList;
	// 路径导航栏中的下拉窗口内容
	private LinearLayout mLlDropDownList;
	// 路径导航栏下拉、上拉的箭头
	private ImageView mIvPathArrow;
	// 返回到上一级按钮
	private ImageView mIvBackUpLevel;

	// ==============内容区域==============
	// 文件列表控件
	private ListView mLvFileList;
	// 没有SD卡提示
	private LinearLayout mLlSdNotAvailable;

	// ==============底部区域==============
	private Button mBtnSendFiles;
	private TextView mTvCheckSize;

	// ==============路径管理==============
	// 当前目录
	private String mCurrentPath;
	// 根目录
	private String mRoot;
	// 上一页的路径
	private String mPreviousPath;// 记住以前的滚动位置路径
	// 记录已选文件的大小
	private long mCheckedFileSize; 

	// ==============列表数据==============
	// 文件列表
	private ArrayList<FileExplorerInfo> mFileNameList = new ArrayList<FileExplorerInfo>();
	// 文件列表适配器
	private FileListAdapter mAdapter;
	// 记录滚动位置
	private ArrayList<PathScrollPositionItem> mScrollPositionList = new ArrayList<PathScrollPositionItem>();
	// 已选择的文件信息列表
	private ArrayList<FileExplorerInfo> mCheckedFileNameList = new ArrayList<FileExplorerInfo>();

	/**
	 * 记录列表滚动位置和路径的类
	 * 
	 * @ClassName PathScrollPositionItem
	 * @Function TODO ADD FUNCTION
	 * @Reason TODO ADD REASON
	 * 
	 * @author HuangYK
	 * @version v1.3.3
	 * @Date 2014-1-27 下午3:51:29
	 * 
	 * @see
	 */
	private class PathScrollPositionItem {
		String path;// 路径
		int pos;// 位置

		PathScrollPositionItem(String s, int p) {
			path = s;
			pos = p;
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mActivity = (FileExplorerActivity) getActivity();
		mRootView = inflater.inflate(R.layout.fragment_file_explorer,
				container, false);
		mFileIconHelper = new FileIconHelper(mActivity);
		mFileSortHelper = new FileSortHelper();

		initView();
		getIntentData();
		initData();
		initEvent();
		return mRootView;
	}

	private void initView() {
		initNaivgationBar();
		mLlSdNotAvailable = (LinearLayout) getViewById(R.id.llNavigationBar);
		mIvBack = (ImageView) getViewById(R.id.ivBack);
		mLvFileList = (ListView) getViewById(R.id.lvFileList);
		mBtnSendFiles = (Button) getViewById(R.id.btnSendFiles);
		mTvCheckSize = (TextView) getViewById(R.id.tvCheckSize);
	}

	private void initNaivgationBar() {
		mLlNavigationBar = (LinearLayout) getViewById(R.id.llNavigationBar);
		mTvCurPath = (TextView) getViewById(R.id.tvCurPath);
		mIvPathArrow = (ImageView) getViewById(R.id.ivPathArrow);
		mLlCurPathPane = (LinearLayout) getViewById(R.id.llCurPathPane);
		mSvDropDownList = (ScrollView) getViewById(R.id.svDropDownList);
		mLlDropDownList = (LinearLayout) getViewById(R.id.llDropDownList);
		mIvBackUpLevel = (ImageView) getViewById(R.id.ivBackUpLevel);
	}

	private void getIntentData() {
		Intent intent = mActivity.getIntent();
		// 设置根目录处于哪个层级
		setRootPath(FileExplorerUtil.ROOT_PATH);
		// 默认当前目录为SD卡目录
		mCurrentPath = SdCardUtils.getSdCardPath();
		// 如果是其他界面跳转过来，解析是否传递过来默认打开的路径
		if (intent.getExtras() != null) {
			mCurrentPath = intent.getStringExtra(CUR_PATH);
		}
	}

	private void initData() {
		mAdapter = new FileListAdapter(mActivity, mFileNameList,
				mFileIconHelper);
		mLvFileList.setAdapter(mAdapter);
		System.out.println("122222222222");
		refreshFileList();
		System.out.println("333333333333333");
	}

	private void initEvent() {
		mIvBack.setOnClickListener(onClick);
		mLlCurPathPane.setOnClickListener(onClick);
		mIvBackUpLevel.setOnClickListener(onClick);
		mBtnSendFiles.setOnClickListener(onClick);

		mLvFileList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				onListItemClick(parent, view, position, id);
			}
		});
	}

	private void setRootPath(String path) {
		mRoot = path;
		mCurrentPath = path;
	}

	@SuppressLint("ShowToast")
	private void onListItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		FileExplorerInfo lFileInfo = getItem(position);
		showDropdownNavigation(false);

		if (lFileInfo == null) {
			return;
		}
		// 如果点击的不是文件夹，就选中。如果是文件夹则刷新
		if (!lFileInfo.IsDir) {
			boolean selected = lFileInfo.Selected;
			// ImageView checkBox = (ImageView)
			// view.findViewById(R.id.ivSelect);
			if (selected) {
				mCheckedFileSize -= lFileInfo.fileSize;
				mCheckedFileNameList.remove(lFileInfo);
				// checkBox.setImageResource(R.drawable.btn_check_off_holo_light);
			} else {
				if(mCheckedFileNameList.size()>MAX_UPLOAD_FILES){
					ToastUtils.display(R.string.upload_max);
					return;
				}else{
					mCheckedFileSize += lFileInfo.fileSize;
					mCheckedFileNameList.add(lFileInfo);
				}
				// checkBox.setImageResource(R.drawable.btn_check_on_holo_light);
			}
			mTvCheckSize.setText(FileExplorerUtil.convertStorage(mCheckedFileSize));
			lFileInfo.Selected = !selected;
			mAdapter.notifyDataSetChanged();

			return;
		} else {
			mCurrentPath = getAbsoluteName(mCurrentPath, lFileInfo.fileName);
			refreshFileList();
		}
	}

	private void refreshFileList() {
		// clearSelection();
		updateNavigationPane();
		onRefreshFileList();
	}

	private void updateNavigationPane() {
		mIvBackUpLevel
				.setVisibility(mRoot.equals(mCurrentPath) ? View.INVISIBLE
						: View.VISIBLE);
		mIvPathArrow.setVisibility(mRoot.equals(mCurrentPath) ? View.GONE
				: View.VISIBLE);
		mTvCurPath.setText(mCurrentPath);
	}

	private void clearSelection() {
		if (isInSelection()) {
			for (FileExplorerInfo f : mCheckedFileNameList) {
				if (f == null) {
					continue;
				}
				f.Selected = false;
			}
			mCheckedFileNameList.clear();
			onDataChanged();
		}
	}

	/**
	 * 获取绝对路径
	 * 
	 * @n<b>函数名称</b> :getAbsoluteName
	 * @brief
	 * @see
	 * @version Ver 1.3.3
	 * @param @param path
	 * @param @param name
	 * @param @return
	 * @return String
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2014-1-27下午3:55:15
	 */
	private String getAbsoluteName(String path, String name) {
		return path.equals(FileExplorerUtil.ROOT_PATH) ? path + name : path
				+ File.separator + name;
	}

	/**
	 * 执行返回操作
	 * 
	 * @n<b>函数名称</b> :onBackPressed
	 * @brief
	 * @see
	 * @version Ver 1.3.x
	 * @param @return
	 * @return boolean
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2014-1-27下午5:57:00
	 */
	private boolean onBackPressed() {
		if (mSvDropDownList.getVisibility() == View.VISIBLE) {
			mSvDropDownList.setVisibility(View.GONE);
		}else if (!doBackUpLevel()) {
			return false;
		}
		return true;
	}

	/**
	 * 是否是在选择状态下
	 * 
	 * @n<b>函数名称</b> :isInSelection
	 * @brief
	 * @see
	 * @version Ver 1.3.3
	 * @param @return
	 * @return boolean
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2014-1-27下午3:44:32
	 */
	private boolean isInSelection() {
		return mCheckedFileNameList.size() > 0;
	}

	public boolean onBack() {
		// if (mBackspaceExit || !FileExplorerUtil.isSDCardReady()) {
		// return false;
		// }
		return onBackPressed();
	}

	/**
	 * 执行之前修改, 返回记忆滚动的位置
	 * 
	 * @n<b>函数名称</b> :computeScrollPosition
	 * @brief
	 * @see
	 * @version Ver 1.3.3
	 * @param @param path
	 * @param @return
	 * @return int
	 * @<b>作者</b> : HuangYK
	 * @<b>创建时间</b> : 2014-1-24下午12:23:54
	 */
	private int computeScrollPosition(String path) {
		int pos = 0;
		if (mPreviousPath != null) {
			if (path.startsWith(mPreviousPath)) {
				int firstVisiblePosition = mLvFileList
						.getFirstVisiblePosition();
				if (mScrollPositionList.size() != 0
						&& mPreviousPath.equals(mScrollPositionList
								.get(mScrollPositionList.size() - 1).path)) {
					mScrollPositionList.get(mScrollPositionList.size() - 1).pos = firstVisiblePosition;
					pos = firstVisiblePosition;
				} else {
					mScrollPositionList.add(new PathScrollPositionItem(
							mPreviousPath, firstVisiblePosition));
				}
			} else {
				int i;
				for (i = 0; i < mScrollPositionList.size(); i++) {
					if (!path.startsWith(mScrollPositionList.get(i).path)) {
						break;
					}
				}
				// 导航到一个全新的分支,而不是在当前堆栈
				if (i > 0) {
					pos = mScrollPositionList.get(i - 1).pos;
				}
				for (int j = mScrollPositionList.size() - 1; j >= i - 1
						&& j >= 0; j--) {
					mScrollPositionList.remove(j);
				}
			}
		}
		mPreviousPath = path;
		return pos;
	}

	private boolean onRefreshFileList() {
		mLvFileList.setVisibility(View.INVISIBLE);
		if (TextUtils.isEmpty(mCurrentPath))
			return false;
		File file = new File(mCurrentPath);
		if (!file.exists() || !file.isDirectory()) {
			return false;
		}
		final int pos = computeScrollPosition(mCurrentPath);
		ArrayList<FileExplorerInfo> fileList = mFileNameList;
		fileList.clear();

		File[] listFiles = file.listFiles();
		if (listFiles == null)
			return true;

		for (File child : listFiles) {
			String absolutePath = child.getAbsolutePath();
			if (FileExplorerUtil.isNormalFile(absolutePath)) {
				FileExplorerInfo lFileInfo = FileExplorerUtil
						.GetFileInfo(child);
				if (lFileInfo != null) {
					fileList.add(lFileInfo);
				}
			}
		}
		sortCurrentList(mFileSortHelper);
		showEmptyView(fileList.size() == 0);
		mLvFileList.post(new Runnable() {
			@Override
			public void run() {
				mLvFileList.setSelection(pos);
				mLvFileList.setVisibility(View.VISIBLE);
			}
		});
		return true;
	}

	private OnClickListener onNavigationClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			String path = (String) v.getTag();
			showDropdownNavigation(false);
			if (path == null)
				return;

			if (path.isEmpty()) {
				mCurrentPath = mRoot;
			} else {
				mCurrentPath = path;
			}
			refreshFileList();
		}

	};

	private View.OnClickListener onClick = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			if (v.getId() == R.id.llCurPathPane) {
				onNavigationBarClick();
			}
			if (id == R.id.ivBackUpLevel) {
				doBackUpLevel();
			}
			if (id == R.id.btnSendFiles) {
				if (mCheckedFileNameList.size() > 0) {
					ArrayList<String> checkPaths = new ArrayList<String>();
					for (FileExplorerInfo info : mCheckedFileNameList) {
						checkPaths.add(info.filePath);
					}
					Intent data = new Intent();
					data.putStringArrayListExtra("paths", checkPaths);
					mActivity.setResult(Activity.RESULT_OK, data);
					mActivity.finish();
				} else {
					
				}
				return;
			}
			if(id == R.id.ivBack){
				mActivity.finish();
			}
		}

	};

	/**
	 * 导航条点击操作处理
	 */
	protected void onNavigationBarClick() {
		if (mSvDropDownList.getVisibility() == View.VISIBLE) {
			showDropdownNavigation(false);
		} else {
			mLlDropDownList.removeAllViews();
			int pos = 0;
			String displayPath = mCurrentPath;
			boolean root = true;
			int left = 0;
			// 如果当前位置在根文件夹则不显示导航条
			while (pos != -1 && !displayPath.equals("/")) {
				int end = displayPath.indexOf("/", pos);
				if (end == -1)
					break;
				View listItem = LayoutInflater.from(mActivity).inflate(
						R.layout.dropdown_item, null);
				View llDropDownItem = listItem
						.findViewById(R.id.llDropDownItem);
				llDropDownItem.setPadding(left, 0, 0, 0);
				left += 20;
				ImageView ivItemIcon = (ImageView) listItem
						.findViewById(R.id.ivItemIcon);
				ivItemIcon
						.setImageResource(root ? R.drawable.dropdown_icon_root
								: R.drawable.dropdown_icon_folder);
				root = false;
				TextView tvPathName = (TextView) listItem
						.findViewById(R.id.tvPathName);
				String substring = displayPath.substring(pos, end);
				if (substring.isEmpty())
					substring = "/";
				tvPathName.setText(substring);
				listItem.setOnClickListener(onNavigationClick);
				listItem.setTag(displayPath.substring(0, end));
				pos = end + 1;
				mLlDropDownList.addView(listItem);
			}
			if (mLlDropDownList.getChildCount() > 0)
				showDropdownNavigation(true);

		}
	}

	private boolean doBackUpLevel() {
		showDropdownNavigation(false);
		if (!mRoot.equals(mCurrentPath)) {
			mCurrentPath = new File(mCurrentPath).getParent();
			refreshFileList();
			return true;
		}
		return false;
	}

	private void showDropdownNavigation(boolean show) {
		mSvDropDownList.setVisibility(show ? View.VISIBLE : View.GONE);
		mIvPathArrow
				.setImageResource(mSvDropDownList.getVisibility() == View.VISIBLE ? R.drawable.path_arrow_up
						: R.drawable.path_arrow_down);
	}

	private void showEmptyView(boolean show) {
		View emptyView = mRootView.findViewById(R.id.empty_view);
		if (emptyView != null)
			emptyView.setVisibility(show ? View.VISIBLE : View.GONE);
	}

	private View getViewById(int id) {
		return mRootView.findViewById(id);
	}

	private void onDataChanged() {
		mAdapter.notifyDataSetChanged();
	}

	private FileExplorerInfo getItem(int pos) {
		if (pos < 0 || pos > mFileNameList.size() - 1)
			return null;

		return mFileNameList.get(pos);
	}

	private void sortCurrentList(FileSortHelper sort) {
		Collections.sort(mFileNameList, sort.getComparator());
		onDataChanged();
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}
}
